﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using HQPad.Controllers;

namespace HQPad.Security
{
    public class LogonAuthorize : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            bool isAdmin = (
                filterContext.Controller is AdminController ||
                filterContext.Controller is InvocationController ||
                filterContext.Controller is SpellController ||
                filterContext.Controller is SkillController);

            if (isAdmin &&
                !filterContext.HttpContext.User.IsInRole("Admin"))
            {
                filterContext.Result = new HttpUnauthorizedResult();
                return;
            }

            bool skipAuthorization = 
                filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || 
                filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
            
            if (!skipAuthorization)
            {
                base.OnAuthorization(filterContext);
            }
        }


    }

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class AllowAnonymousAttribute : Attribute { }
}